/**
 * 
 */
package com.vision.core.sv.serv.rpc.handler;

import static com.vision.core.cm.data.AdminPermissions.UpdateUser;

import java.util.List;

import net.customware.gwt.dispatch.server.ExecutionContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.vision.core.cm.action.AssignRolesToUserAction;
import com.vision.core.cm.action.AssignRolesToUserResult;
import com.vision.core.cm.db.data.Role;
import com.vision.core.cm.db.data.User;
import com.vision.core.cm.exception.DispatchException;

/**
 * @author Mark
 *
 */
@Component
public class AssignRolesToUserHandler extends UserHandler<AssignRolesToUserAction, AssignRolesToUserResult> {
	
	private static final Logger log = LoggerFactory.getLogger(AssignRolesToUserHandler.class);
	
	@Override
	public Class<AssignRolesToUserAction> getActionType() {
		return AssignRolesToUserAction.class;
	}
	
	@Transactional // Ensures that all database operations are done as one transaction
	@Override
	public AssignRolesToUserResult execute(AssignRolesToUserAction action, ExecutionContext context) throws DispatchException {
		checkPermissions(UpdateUser);
		
		User user = action.getUser();
		List<Role> roles = action.getRoles();
		
		User existing = ensureExisting(user);
		for (Role role : roles)
			existing.addRole(role);
		
		log.debug("Assigning roles to user: {}", existing.getUsername());
				
		dataManager.update(existing);
				
		logAssociate(existing, roles);
		
		return new AssignRolesToUserResult(user, roles);
	}
	
}